<!DOCTYPE HTML>
<html>
<head>
    <title>题库</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <link href="../static/assets3/css/bs3/dpl-min.css" rel="stylesheet" type="text/css"/>
    <link href="../static/assets3/css/bs3/bui-min.css" rel="stylesheet" type="text/css"/>
    <link href="../static/assets/css/page-min.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="../admin/css/uploadify.css">
    <link rel="stylesheet" href="../static/layer/skin/default/layer.css" />
</head>
<body>
<div class="container">
    <div class="row">
        <form id="searchForm" class="form-horizontal span24">
            <div class="row">
                <div class="control-group span8">
                    <label class="control-label">题目</label>

                    <div class="controls">
                        <input type="text" class="control-text" name="key" placeholder="题目">
                        <input type="text" name="aaa" style="display: none;">
                    </div>
                </div>
                <div class="span3 offset">
                    <button type="button" id="btnSearch" class="button button-primary">搜索</button>
                </div>
            </div>
        </form>
    </div>
    <div class="toolbar">
        <button id="btnUser" class="button button-primary">用户记录</button>
        <button id="btnPrize" class="button button-primary">中奖记录</button>
    </div>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>


    <div id="content" class="hide">
        <form id="J_Form" class="form-horizontal" method="post">
            <input type="hidden" name="id">

            <!--<div class="row">
                <div class="control-group span8">
                    <input type="hidden" id="input11" name="img" data-rules="{required:true}"
                           class="input-normal control-text"/>
                    <label class="control-label">图片展示</label>

                    <div class="controls" style="width:140px;height:140px">
                        <div id="pic11" style="display:none;"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="control-group span15">
                    <label class="control-label">&nbsp;</label>

                    <div class="controls" style="width:110px;height:110px">
                        <img name="uploadify" id="uploadify" type="file"/>
                    </div>
                </div>
            </div>-->
            <div class="row">
                <div class="control-group span8">
                    <label class="control-label"><s>*</s>题目</label>

                    <div class="controls">
                        <input name="subject" type="text" data-rules="{required:true}"
                               class="input-normal control-text">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="control-group span8">
                    <label class="control-label"><s>*</s>排序数值</label>

                    <div class="controls">
                        <input name="sort" type="text" data-rules="{required:true,number : true,min:1}"
                               class="input-normal control-text">
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript" language="javascript" src="../static/common/jquery.min-2.1.3.js"></script>
<script type="text/javascript" src="../static/layer/layer.js"></script>
<script type="text/javascript" src="../admin/js/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="../static/assets/js/bui.js"></script>
<script type="text/javascript" src="../static/assets/js/config.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#uploadify").uploadify({
            'uploader': '../UploadFile.shtml', 		//后台处理程序的相对路径
            'swf': '../admin/swf/uploadify.swf',  	//flash文件的相对路径
            'height': 25,
            'whith': 100,
            'fileObjName': 'file', 							//设置上传文件名称
            'queueSizeLimit': 1, 							//当允许多文件生成时，设置选择文件的个数，默认值：999
            'fileTypeDesc': '*.jpg;*.gif;*.png;*.jpeg', 	//用来设置选择文件对话框中的提示文本
            'fileTypeExts': '*.jpg;*.gif;*.png;*.jpeg', //设置可以选择的文件的类型
            'auto': true, 									//设置为true当选择文件后就直接上传了，为false需要点击上传按钮才上传
            'multi': false, 								//设置为true时可以上传多个文件
            'uploadLimit': 999,							//可上传次数，默认值：999
            'fileSizeLimit': '2048000000KB',					//上传文件的大小限制
            'buttonText': '上传图片',							//浏览按钮的文本
            'progressData': 'speed',						// ‘percentage’ or ‘speed’.
            'method': 'post',
            'debug': false,
            'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            },
            'onUploadSuccess': function (file, data, response) {
                var jsonobj = eval('(' + data + ')');
                $("#pic11").html("<img src=\"../uploadstart/" + jsonobj[0].trim() + "\" width=\"110\" height=\"110\"/>");
                $("#input11").val(jsonobj[0].trim());
                $("#pic11").removeAttr("style");
            },
            'onUploadError': function (file, errorCode, errorMsg, errorString) {
                alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
            }
        });

        $("#btnUser").on("click",function(){
            window.open("userinfos.html");
        });

        $("#btnPrize").on("click",function(){
            window.open("prizerecords.html");
        });
    });
    BUI.use(['common/search', 'bui/overlay', 'common/page', 'bui/mask'], function (Search, Grid, Data, Overlay, Mask) {
        var Grid = BUI.Grid, Overlay = BUI.Overlay, editing = new Grid.Plugins.DialogEditing({
                    contentId: 'content', //设置隐藏的Dialog内容
                    triggerCls: 'btn-edit', //触发显示Dialog的样式
                    editor: {
                        width: 400,
                        title: '编辑',
                        success: function () {
                            var edtor = this,
                                    form = edtor.get('form'),
                                    editType = editing.get('editType'),//add 或者 edit
                                    url = "";
                            if (editType == 'add') {
                                url = "../question/saveQues";
                            } else if (editType == 'edit') {
                                url = '../question/updateQues';
                            }
                            //检验
                            form.valid();
                            if (form.isValid()) {
                                layer.load();
                                form.ajaxSubmit({ //表单异步提交
                        url: url,
                            success: function (data) {
                        layer.closeAll('loading');
                        if (data.hasError) { //返回的数据是 {hasError : fasle,error : 'xxxx',field : 'xxx'},也可以是任意格式的数据如 ： {success : false,'error' : 'xxxxx'}
                            edtor.close();
                            BUI.Message.Alert(data.error, 'warning');
                        } else {
                            //edtor.accept();
                            edtor.close();
                            store.load();
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.closeAll('loading');
                        BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                    }
                });
                }
            }
        }
    }),
            columns = [
                /*{
                    title: 'logo图', dataIndex: '', elCls: 'center', renderer: function (value, obj) {
                    var logo = Search.createLink({ //链接使用 此方式
                        title: obj.subject,
                        text: "<img src=\"../uploadstart/" + obj.img + "\" width=\"110\" />",
                        href: "../uploadstart/" + obj.img
                    });
                    return logo;
                }
                },*/
                {title: '题目', dataIndex: 'subject', elCls: 'center'},
                {title: '排序', dataIndex: 'sort', elCls: 'center'},
                {
                    title: '操作', dataIndex: '', elCls: 'center', renderer: function (value, obj) {
                    var updStr = "<span class=\"grid-command btn-edit\">编辑</span><br>",
                            ansStr = "<a href=\"answers.html?id=" + obj.id + "&q="+obj.subject+"的\" target='_blank'>答案选项</a>",
                            delStr = '<br><span class="grid-command btn-del" title="删除">删除</span>';//页面操作不需要使用Search.createLink
                    return updStr + ansStr + delStr;
                }
                }
            ],
            store = Search.createStore('../question/listQues', {
                proxy: {
                    save: { //也可以是一个字符串，那么增删改，都会往那么路径提交数据，同时附加参数saveType
                        /* addUrl : '../data/add.json',*/
                        /* updateUrl : ' ', */
                        /* removeUrl : '../data/del.php' */
                    },
                    method: 'POST'
                },
                pageIndex: 0,
                pageSize: 10,
                autoSync: true //保存数据后，自动更新
            }),
            gridCfg = Search.createGridCfg(columns, {
                forceFit: true,
                emptyDataTpl: '<div class="centered"><img alt="Crying" src="http://img03.taobaocdn.com/tps/i3/T1amCdXhXqXXXXXXXX-60-67.png"><h2>查询的数据不存在</h2></div>',
                tbar: {
                    items: [
                        {text: '<i class="icon-plus"></i>新增', btnCls: 'button button-small', handler: addFunction},
                        {
                            text: '<i class="icon-remove"></i>删除',
                            btnCls: 'button button-small',
                            handler: delFunction
                        },
                    ]
                },
                plugins: [editing, BUI.Grid.Plugins.CheckSelection, BUI.Grid.Plugins.AutoFit, Grid.Plugins.ColumnResize] // 插件形式引入多选表格
            });

    var search = new Search({
                store: store,
                gridCfg: gridCfg
            }),
            grid = search.get('grid');

    editing.on('editorshow', function (ev) {
        var type = ev.editType, //add ,edit
                record = editing.get('record');
        //alert(type)
        if (type == 'add') {
            //如果马上保存，通过 ev.editType == 'add' 来判断
        } else {
            //alert(JSON.stringify(record));
           /* $("#pic11").html("<img src=\"../uploadstart/" + record.img + "\" width=\"110\" height=\"110\"/>");
            $("#input11").val(record.img);
            $("#pic11").removeAttr("style");*/
        }
    });

    function addFunction() {
        /*$("#pic11").empty();
        $("#input11").val("");*/
        var newData = {url: "#", sort: 1}; //标志是新增加的记录
        editing.add(newData, 'data'); //添加记录后，直接编辑
    }


    //删除操作
    function delFunction() {
        var selections = grid.getSelection();
        //alert(JSON.stringify(selections));
        delItems(selections);
    }


    function delItems(items) {
        var ids = [];
        BUI.each(items, function (item) {
            ids.push(item.id);
        });
        if (ids.length) {
            BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                layer.load();
                $.ajax({
                    url: "../question/remove",
                    data: {"ids": ids.toString()},
                    dataType: "json",
                    type: "post",
                    async: true,
                        success: function (data) {
                            layer.closeAll('loading');
                            if (data.hasError == false) {
                                store.load();
                            } else {
                                BUI.Message.Alert(data.error, 'warning');
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.closeAll('loading');
                            BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                        }
                    });
                }, 'question');
            } else {
                BUI.Message.Alert("请选择记录", 'warning');
            }
        }

        //监听事件，删除一条记录
        grid.on('cellclick', function (ev) {
            var sender = $(ev.domTarget); //点击的Dom
            if (sender.hasClass('btn-del')) {
                var record = ev.record;
                delItems([record]);
            }
        });

    });
</script>

</body>
</html>  